<template>
  <BasicModal
    v-bind="$attrs"
    title="批量修改菜单所属端"
    :width="700"
    @register="registerInnerModal"
    @ok="handleSubmit"
    @cancel="resetForm"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script setup lang="ts">
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { unref } from 'vue';
  import { menuChangeClientType } from '@/api/system/menu';
  import { clientTypeModalSchemas } from './menu.data';
  import { usePermission } from '@/hooks/web/usePermission';
  import { useLocalStorage } from '@vueuse/core';

  defineOptions({ name: 'MenuModal' });

  // 需要显式写出register 否则会有waning
  // https://doc.vvbin.cn/components/modal.html#usemodal
  const emit = defineEmits(['reload', 'register']);

  const [registerForm, { setFieldsValue, resetForm, getFieldsValue }] = useForm({
    schemas: clientTypeModalSchemas,
    showActionButtonGroup: false,
    labelWidth: 100,
    name: 'menu_client_type_modal',
  });

  const [registerInnerModal, { modalLoading, closeModal }] = useModalInner(
    async (data: { record?: Recordable }) => {
      modalLoading(true);
      const { record } = data;
      if (record) {
        console.log(record);
        await setFieldsValue({ menuIds: record });
      }
      modalLoading(false);
    },
  );

  // 添加/更新后刷新菜单栏 不使用location.reload整页刷新
  const { refreshMenu } = usePermission();
  /** 修改后是否刷新菜单栏 */
  const refreshMenuRef = useLocalStorage('refreshMenu', true);

  async function handleSubmit() {
    try {
      modalLoading(true);
      const data = await getFieldsValue();
      console.log(getFieldsValue());
      await menuChangeClientType(data);
      emit('reload');
      closeModal();
      await resetForm();
      if (unref(refreshMenuRef)) {
        await refreshMenu();
      }
    } catch (e) {
    } finally {
      modalLoading(false);
    }
  }
</script>

<style scoped></style>
